package com.mxnet.chongjin.supoman.activity;

import android.Manifest;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.bean.RepairRecord;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.style.XDialog;
import com.mxnet.chongjin.supoman.utils.BitmapUtils;
import com.mxnet.chongjin.supoman.utils.DpAndPxUtils;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class RepairRecordDefaultActivity extends AppCompatActivity implements View.OnClickListener {
    private Context mContext;
    private LinearLayout mLinearLayout, mLayoutAdd;
    private FrameLayout mFrameLayout;
    private Button mButton;
    private EditText mEditText1, mEditText2;
    private String declarationNo, machineNo;
    public static final int FLAG_TAKE_PHOTO = 0;
    public static final int FLAG_CHOOSE_IMG = 1;
    public static final int FLAG_OTHER = 2;
    private File file;
    private String photoPath;
    private static final int REQUEST_CAMERA = 0;
    private static final String SAVED_IMAGE_PATH = "takephoto";
    private boolean isLogin;
    private List<RepairRecord.ImgResourceBean> mList;
    private List<String> mFaultsList;
    private List<Bitmap> mViewList;
    private List<File> mFileList;
    private TextView mTextView;
    private int tyr = 0;
    private String parts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_record_default);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = RepairRecordDefaultActivity.this;
        declarationNo = getIntent().getStringExtra("recordNo");
        machineNo = getIntent().getStringExtra("machineNo");

        initData();
        initView();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_repair_record_default);
        mLinearLayout.setOnClickListener(this);

        mTextView = findViewById(R.id.tv_repair_record_default_partner_parts);

        mFrameLayout = findViewById(R.id.fl_repair_record_default);
        mFrameLayout.setOnClickListener(this);

        mButton = findViewById(R.id.btn_repair_record_default_save);
        mButton.setOnClickListener(this);

        mEditText1 = findViewById(R.id.et_repair_record_default_machine_num);
        mEditText1.setText(machineNo);

        mEditText2 = findViewById(R.id.et_repair_record_default_fault_detail);

        mLayoutAdd = findViewById(R.id.ll_repair_record_default_faults);

        mViewList.add(BitmapFactory.decodeResource(getResources(), R.mipmap.add));

        addImageView(mLayoutAdd);
    }

    public void initData() {
        mList = new ArrayList<>();
        mFaultsList = new ArrayList<>();
        mViewList = new ArrayList<>();
        mFileList = new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_repair_record_default:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.fl_repair_record_default:
                Intent intent = new Intent();
                intent.setClass(mContext, PartsActivity.class);
                intent.putExtra("fromTag", 1003);
                startActivityForResult(intent, 1003);
                break;
            case R.id.btn_repair_record_default_save:
                if (!TextUtils.isEmpty(mEditText1.getText()) && !TextUtils.isEmpty(mEditText2.getText())) {
                    OkHttpUtils.get()
                            .url(Api.URL_HEADER + Api.WRITE_REPAIR_RECORD_DEFAULT)
                            .addParams("declarationNo", declarationNo)
                            .addParams("maintenanceMemo", mEditText2.getText().toString())
                            .addParams("resourceIdList", new Gson().toJson(mFaultsList))
                            .addParams("changePartsList", parts)
                            .build().execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            new Thread() {
                                public void run() {
                                    try {
                                        Instrumentation inst = new Instrumentation();
                                        inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                        }
                    });
                } else {
                    ToastUtils.showToast(mContext, getResources().getString(R.string.maintain_complete));
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        parts = data.getStringExtra("parts");
        if (requestCode == 1003 && resultCode == 1004) {
            final String partStr = (String) TextUtils.ellipsize(parts, (TextPaint) mTextView.getPaint(), mTextView.getMeasuredWidth() - 10, TextUtils.TruncateAt.END);
            if (partStr != null) {
                mTextView.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(partStr);
                    }
                });
            }
        }
        if (requestCode == FLAG_TAKE_PHOTO && resultCode == RESULT_OK) {
            //在手机相册中显示刚拍摄的图片
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(file);
                String path = contentUri.getPath();
                //文件的路径
                String absolutePath = file.getAbsolutePath();
                //文件的名字
                String parent = file.getName();
                mediaScanIntent.setData(contentUri);
                sendBroadcast(mediaScanIntent);
                //设置图片
                mViewList.add(BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()), 90));
                addImageView(mLayoutAdd);
                mFileList.add(file);
                File f = BitmapUtils.saveImage("headIcon" + System.currentTimeMillis(), BitmapFactory.decodeFile(file.getAbsolutePath()));
                OkHttpUtils.post()
                        .addFile("headIcon", f.getName(), f)
                        .url(Api.URL_HEADER + Api.UPLOAD_IMG)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean success = jsonObject.optBoolean("success");
                                        if (success) {
                                            JSONObject data = jsonObject.optJSONObject("data");
                                            RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                            imgResourceBean.setCreateTime(data.optLong("createTime"));
                                            imgResourceBean.setFileType(data.optString("fileType"));
                                            imgResourceBean.setId(data.optString("id"));
                                            imgResourceBean.setMd5(data.optString("md5"));
                                            imgResourceBean.setName(data.optString("name"));
                                            imgResourceBean.setSize(data.optString("size"));
                                            imgResourceBean.setType(data.optString("type"));
                                            imgResourceBean.setUrl(data.optString("url"));
                                            imgResourceBean.setUserId(data.optString("userId"));
                                            mFaultsList.add(data.optString("id"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
            } else {
                File photoFile = new File(photoPath);
                if (photoFile.exists()) {
                    //通过图片地址将图片加载到bitmap里面
                    Bitmap bm = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                    //将拍摄的照片显示到界面上
                    //这是返回来的路径
                    //                    results.confirm(pathsa);
                    ToastUtils.showToast(mContext, "通过");
                } else {
                    ToastUtils.showToast(mContext, "图片文件不存在");
                }
            }
        } else if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                //                crop(uri);
                try {
                    mViewList.add(BitmapUtils.getBitmapFormUri(mContext, uri));
                    addImageView(mLayoutAdd);
                    final File file1 = uri2File(uri);
                    OkHttpUtils.post()
                            .addFile("headIcon", file1.getName(), file1)
                            .url(Api.URL_HEADER + Api.UPLOAD_IMG)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    if (!TextUtils.isEmpty(response)) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            boolean success = jsonObject.optBoolean("success");
                                            if (success) {
                                                JSONObject data = jsonObject.optJSONObject("data");
                                                RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                                imgResourceBean.setCreateTime(data.optLong("createTime"));
                                                imgResourceBean.setFileType(data.optString("fileType"));
                                                imgResourceBean.setId(data.optString("id"));
                                                imgResourceBean.setMd5(data.optString("md5"));
                                                imgResourceBean.setName(data.optString("name"));
                                                imgResourceBean.setSize(data.optString("size"));
                                                imgResourceBean.setType(data.optString("type"));
                                                imgResourceBean.setUrl(data.optString("url"));
                                                imgResourceBean.setUserId(data.optString("userId"));
                                                mFaultsList.add(data.optString("id"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                    mFileList.add(file1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } else if (requestCode == FLAG_OTHER && resultCode == RESULT_OK) {
            if (data != null) {
                final Bitmap bitmap = data.getParcelableExtra("data");
                mViewList.add(bitmap);
                addImageView(mLayoutAdd);
                mFileList.add(BitmapUtils.saveImage("headIcon" + tyr, bitmap));
                tyr++;
            }
            try {
                if (file != null && file.exists())
                    file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void applyWritePermission() {

        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};

        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            int check2 = ContextCompat.checkSelfPermission(this, permissions[1]);
            int check3 = ContextCompat.checkSelfPermission(this, permissions[2]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED && check2 == PackageManager.PERMISSION_GRANTED && check3 == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                useCamera();
            } else {
                requestPermissions(permissions, 1);
            }
        } else {
            useCamera();
        }
    }

    /**
     * 拍照的，照片路径
     */
    public void jsPath() {
        //获取SD卡安装状态
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {

            //设置图片保存路径
            photoPath = SAVED_IMAGE_PATH + "/" + System.currentTimeMillis() + ".png";

            File imageDir = new File(photoPath);
            if (!imageDir.exists()) {
                try {
                    //根据一个 文件地址生成一个新的文件用来存照片
                    imageDir.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //实例化intent,指向摄像头
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //根据路径实例化图片文件
            File photoFile = new File(photoPath);
            //设置拍照后图片保存到文件中
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            //启动拍照activity并获取返回数据
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ToastUtils.showToast(mContext, "SD卡未插入");
        }
    }

    /**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();
        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.mxnet.chongjin.supoman.fileprovider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
                return;
            }
        }
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
            ToastUtils.showToast(mContext, "需要存储权限");
        }
    }

    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    private void addImageView(LinearLayout linearLayout) {
        linearLayout.removeAllViews();
        LinearLayout layout = null;
        for (int i = 0, j = mViewList.size() - 1; i < mViewList.size() && j >= 0; i++, j--) {
            ImageView iv = new ImageView(mContext);
            iv.setImageBitmap(mViewList.get(j));
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                    DpAndPxUtils.dip2px(mContext, 75f),
                    DpAndPxUtils.dip2px(mContext, 75f));
            params1.setMargins(0, DpAndPxUtils.dip2px(mContext, 15f), DpAndPxUtils.dip2px(mContext, 15f), 0);
            iv.setLayoutParams(params1);
            if (i % 4 == 0) {
                layout = new LinearLayout(mContext);
                layout.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.addView(layout);
            }
            layout.addView(iv);
            if (j == 0) {
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mViewList.size() < 10) {
                            XDialog xDialog = new XDialog(mContext, R.layout.xdialog_change_head_img, new int[]{R.id.btn_change_head_img_take_photo, R.id.btn_change_head_img_choose_from_photoalbum, R.id.btn_change_head_img_cancel});
                            xDialog.setCanceledOnTouchOutside(true);
                            xDialog.setOnXDialogItemClickListener(new XDialog.OnXDialogItemClickListener() {
                                @Override
                                public void OnXDialogItemClick(XDialog xDialog, View view) {
                                    switch (view.getId()) {
                                        case R.id.btn_change_head_img_take_photo:
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                                applyWritePermission();
                                            } else {
                                                jsPath();
                                            }
                                            break;
                                        case R.id.btn_change_head_img_choose_from_photoalbum:
                                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                                                int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                                                int hasWriteContactsPermission2 = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                                if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED || hasWriteContactsPermission2 != PackageManager.PERMISSION_GRANTED) {
                                                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
                                                    return;
                                                }
                                            }
                                            Intent intent1 = new Intent(Intent.ACTION_PICK);
                                            intent1.setType("image/*");
                                            startActivityForResult(intent1,
                                                    FLAG_CHOOSE_IMG);
                                            break;
                                        case R.id.btn_change_head_img_cancel:
                                            break;
                                    }
                                    xDialog.dismiss();
                                }
                            });
                            xDialog.show();
                        } else {
                            ToastUtils.showToast(mContext, "最多添加九张图片！");
                        }
                    }
                });

            } else {
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //todo 实现点击图片放大功能
                    }
                });
            }
        }
    }
}
